package com.hundun.hddeal.timetask;


import com.aliyuncs.exceptions.ClientException;
import com.hundun.hddeal.dao.*;
import com.hundun.hddeal.entity.*;
import com.hundun.hddeal.util.NoteUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.assertj.core.util.DateUtil.now;

/**
 * 定时任务
 * @author 谢
 */
@Service
@Slf4j
public class Timing {

    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    TaskOrderMapper taskOrderMapper;
    @Autowired
    NextOrderMapper nextOrderMapper;
    @Autowired
    AdUserMapper adUserMapper;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    GzhMapper gzhMapper;
    @Autowired
    MtUserMapper mtUserMapper;
    @Autowired
    OrderMapper orderMapper;

    /**
     * 订单超过反馈时间帮广告方自动确认
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void setStatus() throws ClientException {
        //获取当前时间
        Date curDate = new Date(System.currentTimeMillis());
        List<OrderDetail> list = orderDetailMapper.selectAll();
        for (int i = 0; i < list.size(); i++) {

            //到达保留时间变为待结算
            if (list.get(i).getRealityTgTime() != null) {
                long yy = curDate.getTime() - list.get(i).getRealityTgTime().getTime();
                int time = list.get(i).getRetentionTime();
                if (time <= yy / 1000 / 60 / 60 && list.get(i).getStatus() <= 6) {
                    list.get(i).setStatus((byte) 11);
                    orderDetailMapper.updateByPrimaryKeySelective(list.get(i));
                }
            }
            if (list.get(i).getTgTime().getTime() < now().getTime() && list.get(i).getStatus() <= 1 && list.get(i).getStatus() != 13
                    ||list.get(i).getBackTime().getTime()<now().getTime() && list.get(i).getStatus()== 1 && list.get(i).getStatus() != 13) {
                list.get(i).setStatus((byte) 12);
                orderDetailMapper.updateByPrimaryKeySelective(list.get(i));
                Record record = new Record();
                record.setGzhName(list.get(i).getGzhName());
                record.setUserId(list.get(i).getAdId());
                record.setOrderId(list.get(i).getOrderId());
                record.setStatus((byte) 2);
                record.setMoney(list.get(i).getOrderMoney());
                record.setYyName(list.get(i).getNeedName());
                record.setUpdateDate(now());
                record.setContent("退款记录");
                record.setUserFz(list.get(i).getUserFz());
                recordMapper.insertSelective(record);
                //减去冻结金额
                adUserMapper.updateIceMoney(list.get(i).getAdId(), -list.get(i).getOrderMoney());
                //增加用户金额
                adUserMapper.updateMoney(list.get(i).getAdId(), -list.get(i).getOrderMoney());
            }


            //订单响应后不填预览和执行链接，变为流单状态、退钱（5小时短信提醒流单）
            long time = list.get(i).getTgTime().getTime() - curDate.getTime();
            Double newTime = (double) time / 1000 / 60 / 60;

            if (list.get(i).getStatus() == 2 || (list.get(i).getStatus() == 5 && (newTime <= -11.8 && newTime >= -12.2))) {
                if (newTime >= 4.8 && newTime <= 5.2) {
                    log.info("进来了短信");
                    MtUser mtUse = mtUserMapper.selectByMtUserId(list.get(i).getMtId());
                    NoteUtil.sendMessage(mtUse.getMtPhone());
                } else if (newTime <= 0) {
                    list.get(i).setStatus((byte) 12);
                    orderDetailMapper.updateByPrimaryKeySelective(list.get(i));

                    Record record = new Record();
                    record.setGzhName(list.get(i).getGzhName());
                    record.setUserId(list.get(i).getAdId());
                    record.setOrderId(list.get(i).getOrderId());
                    record.setStatus((byte) 2);
                    record.setMoney(list.get(i).getOrderMoney());
                    record.setYyName(list.get(i).getNeedName());
                    record.setUpdateDate(now());
                    record.setContent("退款记录");
                    record.setUserFz(list.get(i).getUserFz());
                    recordMapper.insertSelective(record);
                    //减去冻结金额
                    adUserMapper.updateIceMoney(list.get(i).getAdId(), -list.get(i).getOrderMoney());
                    //增加用户金额
                    adUserMapper.updateMoney(list.get(i).getAdId(), -list.get(i).getOrderMoney());


                }

            }

        }

    }


    /**
     * 任务订单超过推广时间变为待结算状态 有延期状态的即延期推广结束时间 0 0/1 * * * ?  0 0 0/1 * * ?
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void setTgTime() {
        List<TaskOrder> list = taskOrderMapper.selectNewAll();
        //获取当前时间
        Date curDate = new Date(System.currentTimeMillis());
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getTgEndtime().getTime()<=curDate.getTime()) {
                if (list.get(i).getIsPostpone() == 1 && list.get(i).getStatus() != 0) {
                    list.get(i).setTgEndtime(now());
                    taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                } else if (list.get(i).getStatus() == 1 || list.get(i).getStatus() == 2) {
                    //如果没人接单则变为取消且退款 list.get(i).getStatus() != 6 && list.get(i).getStatus() != 8 && list.get(i).getStatus() != 13 &&  list.get(i).getStatus() != 5
                    List<NextOrderPuls> nextOrders = nextOrderMapper.selectGetofTask(null, list.get(i).getOrderId(), null, null, null, null);
                    if (nextOrders.size() == 0) {
                        log.info(list.get(i).getOrderId()+",没人接单进行退款:"+list.get(i).getOutMoney());
                        list.get(i).setStatus((byte) 6);
                        taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                        Record record = new Record();
                        record.setUserId(list.get(i).getAdId());
                        record.setOrderId(list.get(i).getOrderId());
                        record.setStatus((byte) 2);
                        record.setSettMoney(list.get(i).getOutMoney());
                        record.setMoney(list.get(i).getOutMoney());
                        record.setYyName(list.get(i).getAdName());
                        record.setUpdateDate(now());
                        record.setContent("退款记录");
                        record.setUserFz(list.get(i).getUserFz());
                        recordMapper.insertSelective(record);
                        adUserMapper.updateIceMoney(list.get(i).getAdId(), -list.get(i).getOutMoney());
                        adUserMapper.updateMoney(list.get(i).getAdId(), -list.get(i).getOutMoney());
                    } else {
                        log.info(list.get(i).getOrderId()+"结算->大单");
                        list.get(i).setStatus((byte) 4);
                        taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                    }
                 //未付款到达推广时间下架
                }else if(list.get(i).getStatus() == 13){
                    log.info(list.get(i).getOrderId()+"流单->大单");
                    list.get(i).setStatus((byte) 6);
                    list.get(i).setOutMoney(0.00);
                    taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                }


            }
            int time = list.get(i).getRetainTime();
            List<NextOrderPuls> nextOrders = nextOrderMapper.selectGetofTask(null, list.get(i).getOrderId(), null, null, null, null);
            for (int j = 0; j < nextOrders.size(); j++) {
                Double shiji;
                Date realitytime = nextOrders.get(j).getRealityTime();
                if (realitytime != null) {
                    long yy = curDate.getTime() - realitytime.getTime();
                    if (time <= yy / 1000 / 60 / 60 && nextOrders.get(j).getStatus() < 4 && "阅读".equals(nextOrders.get(j).getType())) {
                        log.info("进来阅读任务待结算");
                        log.info("实际阅读量为:"+nextOrders.get(j).getRealityRead());
                        Double money = taskOrderMapper.selectByPrimaryKey(list.get(i).getId()).getRealityMoney();
                            shiji = nextOrders.get(j).getAdPrice() * nextOrders.get(j).getRealityRead();
                            //填入实际收入
                            nextOrderMapper.updateStatus(nextOrders.get(j).getOrder(), (byte) 4, shiji, nextOrders.get(j).getGhId());

                            if (shiji >= nextOrders.get(j).getYjMoney()) {
                                //多出百分之10%
                                double priceOne = nextOrders.get(j).getYjMoney()*0.1;
                                //实际差价
                                double priceTwo = shiji - nextOrders.get(j).getYjMoney();
                                if(priceOne>priceTwo){
                                    list.get(i).setRealityMoney(money + nextOrders.get(j).getYjMoney()+priceTwo);
                                }else {
                                    list.get(i).setRealityMoney(money + nextOrders.get(j).getYjMoney()+priceOne);
                                }
                            }else {
                                list.get(i).setRealityMoney(money + shiji);
                            }


                        //累计加入任务的实际收入
                        taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                    }

                    if (time <= yy / 1000 / 60 / 60 && nextOrders.get(j).getStatus() <=6 && "万粉".equals(nextOrders.get(j).getType())) {
                            log.info("进来万粉任务待结算");
                            Double money = taskOrderMapper.selectByPrimaryKey(list.get(i).getId()).getRealityMoney();
                            //填入实际收入
                            nextOrderMapper.updateStatus(nextOrders.get(j).getOrder(), (byte) 11, nextOrders.get(j).getYjMoney(), nextOrders.get(j).getGhId());
                            list.get(i).setRealityMoney(money + nextOrders.get(j).getYjMoney());
                            //累计加入任务的实际收入
                            taskOrderMapper.updateByPrimaryKeySelective(list.get(i));

                    }

                  //接完阅读任务订单不响应到达推广时间变流单 状态6(现已加多一天添链接时间)
                }else if(nextOrders.get(j).getTgTime().getTime()+ 24 * 3600 * 1000 <= System.currentTimeMillis()){
                    if(nextOrders.get(j).getStatus()!=6 && nextOrders.get(j).getStatus()!=12 && nextOrders.get(j).getStatus()!=0&& nextOrders.get(j).getStatus()!=7){
                        if("万粉".equals(nextOrders.get(j).getType())){
                            log.info(nextOrders.get(j).getOrder()+"万粉流单->小单");
                            nextOrderMapper.updateStatus(nextOrders.get(j).getOrder(), (byte) 12, 0.00, nextOrders.get(j).getGhId());
                        }else {
                            log.info(nextOrders.get(j).getOrder()+"阅读流单->小单");
                            nextOrderMapper.updateStatus(nextOrders.get(j).getOrder(), (byte) 6, 0.00, nextOrders.get(j).getGhId());
                        }
                        //返回到大单预算
                        Double outmoney = list.get(i).getOutMoney();
                        log.info(outmoney+"");
                        list.get(i).setOutMoney(outmoney+nextOrders.get(j).getYjMoney());
                        taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                    }

                }

            }
            if ((list.get(i).getStatus()< 4)) {
                //循环内订单是否全部为待结算状态
                List<NextOrderPuls> nextlist = nextOrderMapper.selectGetofTask(null, list.get(i).getOrderId(), null, null, null, null);
                List<Integer> orders = new ArrayList<>();
                for (NextOrderPuls nextOrderPuls : nextlist) {
                    if (nextOrderPuls.getStatus() >= 4) {
                        orders.add(1);
                    }
                }
                //判断任务单是否金额为零
                if (orders.size() == nextOrders.size() && list.get(i).getOutMoney() == 0) {
                    list.get(i).setStatus((byte) 4);
                    taskOrderMapper.updateByPrimaryKeySelective(list.get(i));
                }
            }


        }
    }


    /**
     * 万粉第一条线未付款时间超过15分钟变为流单
     */
    @Scheduled(cron="0 0/1 * * * ? ")
    public void setOneStatus() {
        //获取当前时间
        Date curDate = new Date(System.currentTimeMillis());
        List<OrderDetail> list = orderDetailMapper.selectAll();
        List<String> orders=new ArrayList<>();
        for (OrderDetail orderDetail : list) {
            if (orderDetail.getStatus() == 13 && (curDate.getTime() - orderDetail.getUpdateDate().getTime()) / 1000 / 60 >= 15) {
                orderDetail.setStatus((byte) 12);
                orderDetailMapper.updateByPrimaryKeySelective(orderDetail);
                if(!orders.contains(orderDetail.getHostId())){
                    orders.add(orderDetail.getHostId());
                }
                log.info("进来15分钟流单-单号："+orderDetail.getOrderId());
            }
        }
        for (String s:orders) {
            orderMapper.updateStatus((byte)4,s,null);
        }

    }



    /**
     * 查看接单平次，扣分或加分
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void setScoreReceipt(){
        //获取当前时间
        Date curDate = new Date(System.currentTimeMillis());
        List <Gzh> gzhs=gzhMapper.selectAllGzh();
        for (Gzh gzh:gzhs) {
            if(gzh.getOrderTime()!=null){
                long yy =curDate.getTime()-gzh.getOrderTime().getTime();
                if(gzh.getScoreReceipt()!=10){
                    //相差多少天
                    if(yy/1000/60/60/24>=1&&yy/1000/60/60/24<=5){
                        //每隔一天增加2分
                        gzh.setScoreReceipt(gzh.getScoreReceipt()+2);
                        gzhMapper.updateByPrimaryKeySelective(gzh);
                    }
                }
            }
        }
    }

    /**
     * 实时更新实际收入 0 0/55 * * * ?
     */
    @Scheduled(cron = "0 0/55 * * * ?")
    public void realTimeNextOrder(){
        List<TaskOrder> list = taskOrderMapper.selectNewAll();
        for (TaskOrder taskOrder:list) {
            Double shiji;
            List<NextOrderPuls> nextOrders = nextOrderMapper.selectGetofTask(null, taskOrder.getOrderId(), null, null, null, null);
            for (NextOrderPuls nextOrderPuls:nextOrders) {
                if("阅读".equals(nextOrderPuls.getType())&&nextOrderPuls.getStatus()==2){
                    shiji = nextOrderPuls.getAdPrice() * nextOrderPuls.getRealityRead();
                    nextOrderMapper.updateStatus(nextOrderPuls.getOrder(), (byte) 2, shiji, nextOrderPuls.getGhId());
                }
            }
        }
    }







}